// houseList.js
const requester = require('../../common/requester.js');
const EventEmitter = require('../../common/EventEmitter.js');
const util = require('../../utils/util.js');
const user = require('../../common/user.js');
const config = require('../../common/config.js');
const formIdInit = require('../../utils/formId.js');
const commonReq = require('../../utils/commonReq.js');
const bookStorage = require('../../utils/bookStorage.js');
const scanCode = require('../../utils/scanCode.js');
const shareCodeHandler = require('../../utils/shareCodeHandler.js');
const $$onLoad = require('../../appLoaded/onLoad');
const app = getApp();

Page({
    published: false,
    data: {
        isAuthed: true,
        formConfig: {
            reportSubmit: true
        },
        publishInfo: {
            count: 0,
            point: 0
        }
    },

    onLoad: function (param) {
        this.param = param;
        formIdInit({
            page: this
        });
        this.init(param);
    },

    onShow: function () {
        if (this.published) {
            wx.switchTab({
                url: '../housePublish/housePublish'
            })
        }
    },

    init: function (param) {
        wx.showLoading();
        let p1 = this.queryMyDefaultAddress();
        let p2 = this.queryBookByIsbn(param.isbn)
            .then(info => {
                this.insertBookStore(info);
                this.updateBookStore();
                return 'insert done'
            }).catch(err => {
                wx.showToast({
                    title: err.msg,
                    icon: 'none',
                    duration: 3000,
                    mask: true
                });
                setTimeout(() => {
                    wx.switchTab({
                        url: '../housePublish/housePublish'
                    })
                }, 3000);
                return Promise.reject();
            });
        let p3 = commonReq.getPageDesc('publishPage')
            .then(res => {
                this.setData({
                    desc: res.data
                });
                return 'desc done';
            });

        Promise.all([p1, p2, p3])
            .then(res => {
                wx.hideLoading();
            })

    },

    queryMyDefaultAddress: function () {
        return requester.request({
            url: config.service.queryMyDefaultAddress,
            method: 'POST',
            header: {
                "Content-Type": "application/x-www-form-urlencoded"
            }
        }).then(res => {
            let address = res.data,
                addressSaved = !!this.data.address;
            if (address && !addressSaved) {
                this.setData({
                    address: {
                        ...address,
                        userName: address.deliveryUserName,
                        detailInfo: address.detailAddress
                    },
                    deliveryAddressId: address.deliveryAddressId
                });
                return 'DefaultAddress done'
            }
        });
    },

    queryBookByIsbn: function (isbn) {
        return requester.request({
            url: requester.service.queryBookByIsbn,
            data: {
                isbn
            }
        }).then(res => {
            wx.hideLoading();
            if (res && res.data) {
                return res.data
            } else {
                return Promise.reject(res);
            }
        })
    },

    insertBookStore: function (bookInfo) {
        let bookInfoStore = bookStorage.getBookStore();
        let unDuplicated = bookInfoStore
            .every(info =>
                info.bookId !== bookInfo.bookId
            );

        if (unDuplicated) {
            bookInfoStore.push(bookInfo);
            bookStorage.setBookStore(bookInfoStore);
        } else {
            /*wx.showToast({
                icon: 'none',
                title: '已经添加过这本书了哦～'
            })*/
        }
    },

    updateBookStore: function () {
        let bookInfoStore = bookStorage.getBookStore();

        let totalInfo = this.calculate(bookInfoStore);
        this.setData({
            totalInfo,
            bookInfoList: bookInfoStore
        })
    },

    calculate: function (bookInfo) {
        let count = bookInfo.length,
            point = 0,
            ids = [];

        bookInfo.forEach(book => {
            point = point + parseInt(book.pointVo.point, 10);
            ids.push(book.bookId);
        });
        ids = ids.join('|');

        return {
            count,
            point,
            ids
        }
    },

    scanCodePublish: function (e) {
        scanCode()
            .then(this.queryBookByIsbn)
            .then(info => {
                this.insertBookStore(info);
                this.updateBookStore();
            });
    },

    deleteBook: function (e) {
        let isbn = e.target.dataset.isbn;
        bookStorage.deleteBookByISBN(isbn);
        this.updateBookStore();
    },

    selectAddress: function () {
        this.chooseAddress()
            .then(address => {
                this.addDeliveryAddress(address)
                    .then(id => {
                        this.setData({
                            address,
                            deliveryAddressId: id
                        });
                    });
            })
            .catch(err => {
                console.log(err);
                let errMsg = err.errMsg.toLowerCase();
                console.log(errMsg.indexOf('address') !== -1, errMsg.indexOf('auth') !== -1)
                if (errMsg.indexOf('address') !== -1 && errMsg.indexOf('auth') !== -1) {
                    wx.showModal({
                        title: '提示',
                        showCancel: false,
                        content: '请先打开通讯地址访问权限～',
                        success: () => {
                            wx.openSetting({
                                success: (res) => {
                                    console.log(res);
                                    if (res.authSetting["scope.address"]) {
                                        setTimeout(() => {
                                            this.selectAddress();
                                        }, 50)
                                    }
                                }
                            })
                        }
                    })
                }
            })
    },

    chooseAddress: function () {
        return new Promise((resolve, reject) => {
            wx.chooseAddress({
                success: (res) => {
                    resolve(res);
                },
                fail: (err) => {
                    reject(err);
                }
            })
        })
    },

    addDeliveryAddress: function (address) {
        return requester.request({
            url: config.service.addDeliveryAddress,
            method: 'POST',
            header: {
                "Content-Type": "application/x-www-form-urlencoded"
            },
            data: {
                deliveryUserName: address.userName,
                telNumber: address.telNumber,
                provinceName: address.provinceName,
                cityName: address.cityName,
                countyName: address.countyName,
                detailAddress: address.detailInfo,
                postCode: address.postalCode
            }
        }).then(res => {
            return res.data.deliveryAddressId;
        }).catch(err => {
            console.log(err);
        });
    },


    publish: function (e) {
        let totalInfo = this.data.totalInfo,
            deliveryAddressId = this.data.deliveryAddressId,
            bookIds = totalInfo && totalInfo.ids;

        if (!deliveryAddressId) {
            wx.showToast({
                title: '请选择发货地址',
                icon: 'none'
            });
            return
        }
        if (!bookIds) {
            wx.showToast({
                title: '请扫码添加图书',
                icon: 'none'
            });
            return
        }
        wx.showLoading({
            title: '正在发布',
            mask: true
        });
        return requester.request({
            url: requester.service.publishProductBooks,
            method: 'POST',
            header: {
                "Content-Type": "application/x-www-form-urlencoded"
            },
            data: {
                bookIds,
                deliveryAddressId
            }
        }).then(res => {
            if (res && res.data) {
                return this.clearPublishStore(res.data);
            } else {
                return Promise.reject(res);
            }
        }).then(res => {
            this.published = true;
            wx.hideLoading();
            wx.navigateTo({
                url: `../housePublishDone/housePublishDone?publishDesc=${res.publishDesc}`
            })
        }).catch(res => {
            wx.hideLoading();
        });
    },

    clearPublishStore: function (res) {
        return new Promise((resolve, reject) => {
            wx.removeStorage({
                key: config.storage.keyBookInfos,
                success: () => {
                    resolve(res);
                },
                fail: (err) => {
                    reject(err);
                }
            })
        });

    },

    onShareAppMessage: function (res) {
        return shareCodeHandler.getShareDetail();
    }
});